//
//  WmcSyncSettingsView.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/9/17.
//

import UIKit
import YPBedrock

// MARK: - [WmcSyncSettingsView]

class WmcSyncSettingsView: UIView {
    // Internal

    var ensureClosure: (([WmcMediaAlbumConfigurationModel]) -> Void)?
    
    var syncTeamCountClosure: ((Int) -> Void)?
    
    enum Style {
        case defaultType
        case confirmType
    }

    @discardableResult
    static func showInView(style: Style, isMustSelected: Bool = false) -> WmcSyncSettingsView {
        let subview = WmcSyncSettingsView()
        subview.style = style
        subview.isMustSelected = isMustSelected

        subview.makeUI()
        subview.makeConstraints()
        subview.fetchData()
        subview.bindEvent()

        return subview
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: 8.yp.cgSize)
        maskLayer.path = maskPath.cgPath
        layer.mask = maskLayer
    }

    // Private

    private var style: Style = .defaultType
    
    private var isMustSelected: Bool = false

    private lazy var defaultHeaderView: UIView = {
        let view = UIView()
        return view
    }()
    
    private lazy var barView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH14_CCCCCC
        view.layer.cornerRadius = 2.5
        view.layer.masksToBounds = true
        return view
    }()

    private lazy var defaultTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "拍照自动同步"
        label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        label.textColor = .wmc_grayH2_323233
        return label
    }()

    private lazy var defaultDescLabel: UILabel = {
        let label = UILabel()
        label.text = "开启后拍照自动同步到团队，永久免费储存！"
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.textColor = .wmc_grayH8_8A8A99
        return label
    }()

    private lazy var confirmHeaderView: UIView = {
        let view = UIView()
        return view
    }()

    private lazy var confirmTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "选择同步的团队"
        label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        label.textColor = .wmc_grayH2_323233
        return label
    }()

    private lazy var confirmStatisticsLabel: UILabel = {
        let label = UILabel()
        label.text = "已选(0)"
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = .wmc_blue_5290FD
        label.textAlignment = .right
        return label
    }()

    private lazy var line: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcSyncSettingsListCell.self, forCellReuseIdentifier: "WmcSyncSettingsListCell")
        view.separatorStyle = .none
        return view
    }()

    private lazy var ensureBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIColor.wmc_blue_5290FD.yp.uiImage(), for: .normal)
        btn.setTitle("确认", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 16.wmc_font
        btn.layer.cornerRadius = 4.0
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(onSureAction(sender:)), for: .touchUpInside)
        return btn
    }()

    private lazy var viewModel: WmcSyncSettingsVM = {
        let vm = WmcSyncSettingsVM()
        return vm
    }()

    private lazy var maskLayer: CAShapeLayer = {
        let maskLayer = CAShapeLayer()
        return maskLayer
    }()

    private func makeUI() {
        self.backgroundColor = .white

        addSubview(defaultHeaderView)
        addSubview(confirmHeaderView)
        addSubview(barView)
        addSubview(line)
        addSubview(tableView)
        addSubview(ensureBtn)

        defaultHeaderView.addSubview(defaultTitleLabel)
        defaultHeaderView.addSubview(defaultDescLabel)
        confirmHeaderView.addSubview(confirmTitleLabel)
        confirmHeaderView.addSubview(confirmStatisticsLabel)
    }

    private func makeConstraints() {
        defaultHeaderView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(75)
        }

        defaultTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(20)
            make.height.equalTo(21)
        }

        defaultDescLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(defaultTitleLabel.snp.bottom).offset(4)
            make.height.equalTo(18)
        }

        confirmHeaderView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(62)
        }

        confirmTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(20)
            make.height.equalTo(21)
        }

        confirmStatisticsLabel.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(confirmTitleLabel)
            make.width.equalTo(100)
            make.height.equalTo(20)
        }
        
        ensureBtn.snp.makeConstraints { make in
            make.bottom.equalTo(-Wmc_safeAreaBottom - 24)
            make.centerX.equalToSuperview()
            make.width.equalTo(165)
            make.height.equalTo(40)
        }
        
        if style == .defaultType {
            defaultHeaderView.isHidden = false
            confirmHeaderView.isHidden = true
            ensureBtn.isHidden = true
            
            line.snp.makeConstraints { make in
                make.left.equalTo(17)
                make.right.equalTo(-17)
                make.top.equalTo(76)
                make.height.equalTo(1)
            }
            
            tableView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(line.snp.bottom)
                make.bottom.equalTo(-Wmc_safeAreaBottom)
            }
        } else {
            defaultHeaderView.isHidden = true
            confirmHeaderView.isHidden = false
            ensureBtn.isHidden = false
            
            line.snp.makeConstraints { make in
                make.left.equalTo(17)
                make.right.equalTo(-17)
                make.top.equalTo(62)
                make.height.equalTo(1)
            }
            
            tableView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(line.snp.bottom)
                make.bottom.equalTo(-Wmc_safeAreaBottom - 88)
            }
        }
        
        barView.snp.makeConstraints { make in
            make.top.equalTo(6)
            make.width.equalTo(48)
            make.height.equalTo(5)
            make.centerX.equalToSuperview()
        }
    }
    
    private func bindEvent() {
        let pan = UIPanGestureRecognizer(target: self, action: #selector(onPanAction(sender:)))
        self.addGestureRecognizer(pan)
    }
    
    private func fetchData() {
        WmcHudManager.loading()
        viewModel.fetchTeamList { [weak self] list in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            weakSelf.tableView.reloadData()
            let count = weakSelf.viewModel.querySelectedCount()
            weakSelf.confirmStatisticsLabel.text = "已选(\(count))"
        } failure: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }
    }
    
    @objc
    private func onSureAction(sender: UIButton) {
        var temp: [WmcMediaAlbumConfigurationModel] = []
        viewModel.dataSource.forEach { model in
            if model.isSync {
                temp.append(model)
            }
        }
        if isMustSelected, temp.isEmpty {
            WmcHudManager.toast("请选择同步的团队")
            return
        }
        YPApp.CurrentVC?.dismiss(animated: true)
        ensureClosure?(temp)
    }
    
    @objc
    private func onPanAction(sender: UIPanGestureRecognizer) {
        let translation : CGPoint = sender.translation(in: self)
        
        if sender.state == .changed {
            if translation.y < 0 {
                return
            }
            self.snp.updateConstraints { make in
                make.bottom.equalTo(translation.y)
            }
        } else if sender.state == .ended {
            var bottom = 0
            let isNeedDismiss = translation.y > 100
            if isNeedDismiss {
                bottom = 373
            }
            UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.snp.updateConstraints { make in
                    make.bottom.equalTo(bottom)
                }
                weakSelf.superview?.layoutIfNeeded()
            } completion: { _ in
                if isNeedDismiss {
                    YPApp.CurrentVC?.dismiss(animated: false)
                }
            }
        }
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmcSyncSettingsView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return viewModel.dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcSyncSettingsListCell = tableView.dequeueReusableCell(withIdentifier: "WmcSyncSettingsListCell", for: indexPath) as! WmcSyncSettingsListCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.row) {
            cell.bindModel(model)
            
            cell.onOffSwitchClosure = { [weak self] data in
                guard let weakSelf = self else { return }
                WmcHudManager.loading()
                weakSelf.viewModel.updateSwitch(model: data.model, isOn: data.isOn) { _ in
                    WmcHudManager.dismiss()
                    WmcPreferenceSettingsManager.updateTeamSyncConfig(model: data.model)
                    
                    weakSelf.viewModel.updateStatus(model: data.model, isOn: data.isOn)
                    weakSelf.tableView.reloadData()
                    
                    let count = weakSelf.viewModel.querySelectedCount()
                    weakSelf.confirmStatisticsLabel.text = "已选(\(count))"
                    
                    let teamCount = weakSelf.viewModel.querySelectdTeamCount()
                    weakSelf.syncTeamCountClosure?(teamCount)
                } failure: { error in
                    WmcHudManager.dismiss()
                    WmcHudManager.toast(error)
                    weakSelf.tableView.reloadData()
                }
            }
        }
        return cell
    }

    func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
        return 57
    }
}
